﻿// 项目：	Guan.CMS.Domain - Guan.CMS
// 文件名：	AddOrUpdateArticleHandler.cs
// 
// 修改时间：2013-03-09 13:23
// 修改人：	Cooclsee

using System;
using System.Web;
using Guan.CMS.CommandProcessor.Command;
using Guan.CMS.Data.Infrastructure;
using Guan.CMS.Data.Repositories;
using Guan.CMS.Domain.Commands.Article;

namespace Guan.CMS.Domain.Handlers.Article
{
    public class AddOrUpdateArticleHandler : ICommandHandler<AddOrUpdateArticleCommand>
    {
        private readonly IArticleRepository _articleRepository;
        private readonly IUnitOfWork _unitOfWork;

        public AddOrUpdateArticleHandler(IArticleRepository articleRepository,
                                         IUnitOfWork unitOfWork)
        {
            this._articleRepository = articleRepository;
            this._unitOfWork = unitOfWork;
        }

        public ICommandResult Execute(AddOrUpdateArticleCommand command)
        {
            var now = DateTime.Now;
            Model.Entities.Article article = null;
            var isAdd = command.Id == 0;
            if (isAdd)
            {
                //Add
                article = new Model.Entities.Article
                {
                    Author = HttpContext.Current.User.Identity.Name,
                    CreatedTime = now
                };
            }
            else
            {
                article = _articleRepository.GetById(command.Id);
            }
            article.Title = command.Title;
            article.UpdatedTime = now;
            article.Body = HttpUtility.HtmlDecode(command.Body);
            article.EndTime = command.EndTime;
            article.Tags = command.Tags;
            article.CategoryId = command.CategoryId==0?(int?) null:command.CategoryId;
            article.IsPublished = command.IsPublished;
            article.MetaTitle = command.MetaTitle;
            article.MetaKeywords = command.MetaKeywords;
            article.MetaDescription = command.MetaDescription;
            article.FriendlyName = command.FriendlyName;
            _articleRepository.AddOrUpdate(article);
            _unitOfWork.Commit();
            return new CommandResult(true);
        }
    }
}